mui.init();
var old_back = mui.back;
mui.back = function(){
    	var indexPage = plus.webview.getLaunchWebview();
    	plus.storage.setItem(KeyCfg.currClickTabId,"userAccount");
    indexPage.show();
    mui.fire(indexPage,'refresh',{});
}

var inputZrl_IdPrefix = "zrl_";	/*折让率文本框ID前缀*/
var btna_IdPrefix = "btnRedeem_";/*赎回按钮ID前缀*/
var btnIds = [];/*赎回按钮ID数组*/
var zrlIdArr = [];/*折让率ID文本框数组*/
init();
function init(){
	initBtnListeners();
}
mui.plusReady(function(){
	 
//	var targetPageId = plus.storage.getItem(KeyCfg.targetPageId);
//	if(!targetPageId){
//		targetPageId = plus.webview.all()[0].id;
//		plus.storage.setItem(KeyCfg.targetPageId,targetPageId);
//	}
//	var targetPageId = plus.webview.currentWebview().id;
//	plus.storage.setItem(KeyCfg.targetPageId,targetPageId);
//	MuiEventMgr.checkSecuity();/*安全认证*/
	if(btnIds && btnIds.length > 0) btnIds = [];
	loadDatas();
});
 
function initBtnListeners(){
	/*---- 同意复选框 ----*/
	var chkImg_iagree = CmwMcore.$('chkImg_iagree');
	//chk_iagree.checked = "true"; 
	MeventMgr.onTouchstart(chkImg_iagree,function(event,self){
		var className = chkImg_iagree.className;
		var checked = "";
		if(className =="cmw_checkbox_checked"){
			className = "cmw_checkbox_empty";
		}else{
			className = "cmw_checkbox_checked";
			checked = "checked";
		}
		CmwMcore.$('iagree').checked = checked;
		chkImg_iagree.className = className;
		return false;
	});
	
	/*---- 确定按钮 ----*/
	var btn_finish = CmwMcore.$('btn_finish');
	MeventMgr.onTouchstart(btn_finish,function(event,self){
		if(!validForm()) return false;
		doFinish();
		return false;
	});
	
	var btn_close = CmwMcore.$('btn_close');
	MeventMgr.onTouchstart(btn_close,function(event,self){
		resetDatas();
		return false;
	});
	
}

mui(".mui-popover ").on("tap", "a", function() {
	var targetPageId = plus.webview.currentWebview().id;
	plus.storage.setItem(KeyCfg.targetPageId,targetPageId);
	var self = this;
	var name=$(self).attr("id");
	switch(name){
		case 'redeem_all':
		     $("#invest0").addClass("activity");
		     $("#invest1").removeClass("activity");
		     $("#invest3").removeClass("activity");
		     $("#invest4").removeClass("activity");
		     $("#invest2").removeClass("activity");
		     loadDatas();
		     mui('#Popover').popover('hide');
		      $("#Popover").css("display","none");
			break;
		case 'redeem_init':
		     $("#invest0").removeClass("activity");
		     $("#invest1").addClass("activity");
		     $("#invest3").removeClass("activity");
		     $("#invest4").removeClass("activity");
		     $("#invest2").removeClass("activity");
		     loadDatas3();
		     mui('#Popover').popover('hide');
		     $("#Popover").css("display","none");
			break;
		case 'redeem_handing':
		      $("#invest0").removeClass("activity");
		      $("#invest1").removeClass("activity");
		      $("#invest4").removeClass("activity");
		      $("#invest3").removeClass("activity");
		      $("#invest2").addClass("activity");
		      loadDatas2();
		      mui('#Popover').popover('hide');
		       $("#Popover").css("display","none");
			break;
		case 'redeem_over':
		      $("#invest0").removeClass("activity");
		      $("#invest1").removeClass("activity");
		      $("#invest2").removeClass("activity");
		      $("#invest0").removeClass("activity");
		      $("#invest3").addClass("activity");
		      $("#invest4").removeClass("activity");
		     loadDatas4();
		      $("#Popover").css("display","none");
		      mui('#Popover').popover('hide');
			break;
		case 'redeem_no':
		      $("#invest0").removeClass("activity");
		      $("#invest1").removeClass("activity");
		      $("#invest2").removeClass("activity");
		      $("#invest3").removeClass("activity");
		      $("#invest4").addClass("activity");
		     loadDatas5();
		      $("#Popover").css("display","none");
		      mui('#Popover').popover('hide');
			break;
		default :{
			 loadDatas();
		     mui('#Popover').popover('hide');
		      $("#Popover").css("display","none");
			break;
		}
	}
});



function resetDatas(){
	if(btnIds && btnIds.length > 0) btnIds = [];
	$("#phoneCode").val("");
	$("#jypassword").val("");
	$("#iagree").removeAttr("checked");
	var chkImg_iagree = CmwMcore.$('chkImg_iagree');
 	if(chkImg_iagree) chkImg_iagree.className = "cmw_checkbox_empty";

}

//债权转让所有数据列表		
function loadDatas(){
	var url = UrlConfig.mforeclosureInve_loanAll;
	// 弹出系统等待对话框   
	//var w = mui.plus.nativeUI.showWaiting( "正在加载..." );
	MuiEventMgr.ajax(url,{pars:{},
	  	sfn : function(data){
	  		callback(data);
	  	},ffn : function(err){
	  		mui.alert("获取数据失败：["+err+"]");
	  		//mui.plus.nativeUI.closeWaiting();
	  	}
	 });
}

function callback(data){
	var msg = data.msg;
	var feeStart = msg.feeStart; 
	var feeEnd = msg.feeEnd;
	var companyfee = msg.companyfee;
	var periodNow = msg.periodNow;
	var periodLeft = msg.periodLeft;
	
	$("#feeStart").val(feeStart);
	$("#feeEnd").val(feeEnd);
	$("#redemptionfeeStart").html(feeStart);
	$("#redemptionfeeEnd").html(feeEnd);
	$("#companyfee").html(companyfee);
	$("#periodNow").html(periodNow);
	$("#periodLeft").html(periodLeft);
	var loanList = msg.loanList;
	if(!loanList || loanList.length == 0){
		var htmlArr = [
				'<div class="cmw_noinvest">暂无记录！</div>'
		];
		var htmlCodes = htmlArr.join("  ");
		$("#item1_loanRecords").html(htmlCodes);
		return;	
	}
	var feeStart = msg.feeStart;
	var feeEnd = msg.feeEnd;
	var htmlArr = [];
	for(var i=0,count=loanList.length; i<count; i++){
		var loanObj = loanList[i];
		var html = getHtml(loanObj,feeStart,feeEnd);
		htmlArr[i] = html;
	}
	var htmlCodes = htmlArr.join("  ");
	$("#item1_loanRecords").html(htmlCodes);
//	addBtnListeners();
	if(zrlIdArr && zrlIdArr.length > 0) initListPicker(feeStart,feeEnd);
}

//债权转让处理中数据列表	
function loadDatas2(){
	var url = UrlConfig.mforeclosureInve_loanAll;
	// 弹出系统等待对话框   
	//var w = mui.plus.nativeUI.showWaiting( "正在加载..." );
	var formDatas = {status:'handing'};
	MuiEventMgr.ajax(url,{pars:formDatas,
	  	sfn : function(data){
	  		callback(data);
	  	},ffn : function(err){
	  		mui.alert("获取数据失败：["+err+"]");
	  		//mui.plus.nativeUI.closeWaiting();
	  	}
	 });
}


//债权转让可赎回数据列表	
function loadDatas3(){
	var url = UrlConfig.mforeclosureInve_loanAll;
	// 弹出系统等待对话框   
	//var w = mui.plus.nativeUI.showWaiting( "正在加载..." );
	var formDatas = {status:'init'};
	MuiEventMgr.ajax(url,{pars:formDatas,
	  	sfn : function(data){
	  		callback(data);
	  	},ffn : function(err){
	  		mui.alert("获取数据失败：["+err+"]");
	  		//mui.plus.nativeUI.closeWaiting();
	  	}
	 });
}

//债权转让已赎回数据列表	
function loadDatas4(){
	var url = UrlConfig.mforeclosureInve_loanAll;
	// 弹出系统等待对话框   
	//var w = mui.plus.nativeUI.showWaiting( "正在加载..." );
	var formDatas = {status:'over'};
	MuiEventMgr.ajax(url,{pars:formDatas,
	  	sfn : function(data){
	  		callback(data);
	  	},ffn : function(err){
	  		mui.alert("获取数据失败：["+err+"]");
	  		//mui.plus.nativeUI.closeWaiting();
	  	}
	 });
}

//债权转让不可赎回数据列表	
function loadDatas5(){
	var url = UrlConfig.mforeclosureInve_loanAll;
	// 弹出系统等待对话框   
	//var w = mui.plus.nativeUI.showWaiting( "正在加载..." );
	var formDatas = {status:'no'};
	MuiEventMgr.ajax(url,{pars:formDatas,
	  	sfn : function(data){
	  		callback(data);
	  	},ffn : function(err){
	  		mui.alert("获取数据失败：["+err+"]");
	  		//mui.plus.nativeUI.closeWaiting();
	  	}
	 });
}

//function addBtnListeners(){
//	
//	if(!btnIds || btnIds.length == 0) return;
//	for(var i=0,count=btnIds.length; i<count; i++){
//		var btnId = btnIds[i];
//		var ele_btn = CmwMcore.$(btnId);
//		MeventMgr.onTouchstart(ele_btn,function(event,self){
//			setData2Win(self.id);
//		});
//	}
//}

/**
 * 为投资赎回窗口赋值  
 * @param btnId 按钮ID
 */
function setData2Win(btnId){
	var loanId = $("#"+btnId).attr("loanID");
	var ele_zrl = $("#"+inputZrl_IdPrefix+loanId);
	var zrl = ele_zrl.val();  
	
	if(!zrl && zrl !== 0){
		mui.alert("请输入折让率");
		ele_zrl.focus();
		return;
	}
	
	var feeStart = $("#feeStart").val();
	var feeEnd = $("#feeEnd").val(); 
	if(parseFloat(zrl) < parseFloat(feeStart) || parseFloat(zrl) > parseFloat(feeEnd)){
		mui.alert("折让率数值必须在"+feeStart+"至"+feeEnd+"之间");
		ele_zrl.focus();
		return;
	}
	resetDatas();
//	var pars = {loanRecordIds:loanId,discounts:zrl};
//	var url = UrlConfig.mforeclosureInve_applyTodoing;
//	MuiEventMgr.ajax(url,{pars:pars,
//	  	sfn : function(data){
//	  		setVals(data);
//	  	},ffn : function(err){
//	  		mui.alert("获取数据失败：["+err+"]");
//	  	} 
//	 });
	var cfg = {pars :{loanRecordIds:loanId,discounts:zrl}};
	MuiEventMgr.openBySafe('redeem_data.html',cfg);
}


function getHtml(loanObj,feeStart,feeEnd){
	//名称
	var loanTitle = loanObj.loanTitle;
	//年化收益率
	var rateYear = loanObj.rateYear;
	//投资金额
	var buyMoney = loanObj.buyMoney;
	buyMoney = CmwMcore.getThousandths(buyMoney);
	//折让率
	var grate = "0.0";
	//借款金额
	var tenderMoney = loanObj.tenderMoney || 0;
	//购买金额
	var receiveMoney = loanObj.receiveMoney || 0;
	//剩余价值
	var xmoney = loanObj.receiveMoney;
	xmoney = xmoney.toFixed(2);

	//赎回金额
	var sellMoney = loanObj.sellMoney || 0;
	
	//状态
	var status = loanObj.status || "";
	
	var statusResult = "";
	switch(status){
		case "init" :{
			statusResult = "可赎回";
			break;
		}case "doing" :{
			statusResult = "申请中";
			break;
		}case "handing" :{
			statusResult = "处理中";
			break;
		}case "over" :{
			statusResult = "已赎回";
			break;
		}case "no" :{
			statusResult = "不可赎回";
			break;
		}default:{
			statusResult = "可赎回";
		}
	}
	if(status == '处理中'){
	   mui.alert(xmoney);
	}
	//转让日期
	var transfersTime = loanObj.transfersTime;
	if(!transfersTime) transfersTime = '';
	//已还期数
	var paidPeriod = loanObj.paidPeriod;
	//总期数
	var totalPeriod = loanObj.totalPeriod;
	//剩余期数
	var leftPeriod = loanObj.totalPeriod - loanObj.paidPeriod;
	//投资记录ID 
	var loanID = loanObj.loanID;
	var mark = loanObj.mark;
	
	
	var subHtmls = null;
	if(status == 'init'){
		var btnAid = btna_IdPrefix + loanID;
		btnIds[btnIds.length] = btnAid;
		
		var btnHtml = '<span class="TitleTwo">状&nbsp;&nbsp;&nbsp;&nbsp;态&nbsp;&nbsp;&nbsp;：</span><a class="TitleTwo" id="'+btnAid+'"  loanID="'+loanID+'"><button type="button" onclick="setData2Win(\''+btnAid+'\');" class="mui-btn btn-orange" style="width: 40%;padding: 4px 12px;margin-top: -2px;">可赎回</button></a>';
		var inputHtml = grate+"%";
        var zrlId = inputZrl_IdPrefix + loanID;
		zrlIdArr[zrlIdArr.length] = zrlId; 
		inputHtml= '<input type="text" id="'+zrlId+'" name="'+zrlId+'" class="zrl_input" value="'+grate+'" onkeyup="CmwMcore.onlyNum(this)"  maxlength="5" readonly="readonly"/>%';			
		subHtmls = [
		'				<div><span class="TitleTwo">赎回金额：</span>——</div>',
		'			</div>',
		'           <div class="cmw_list_row" style="padding-bottom: 30px;">',
		'				<div>',
		'					<span class="TitleTwo zrl_label" style="float:left">折&nbsp;让&nbsp;率&nbsp;&nbsp;：</span>',
							inputHtml,
		'				</div>', 
		'				<div>'+btnHtml+'</div>',
		'			</div>'
		]; 
	}else{// mark = "TransfersLoan"
		var discountRate = loanObj.discountRate;
		var handlingCharge = loanObj.handlingCharge || 0;
		var sfAmount = parseFloat(sellMoney) - parseFloat(handlingCharge);
		sfAmount = CmwMcore.getThousandths(sfAmount);
		subHtmls = [
			'	<div><span class="TitleTwo">赎回金额：￥'+sfAmount+'</span></div>',
			'</div>',
			'<div class="cmw_list_row" style="padding-bottom: 30px;">',
			'	<div><span class="TitleTwo zrl_label">折&nbsp;让&nbsp;率&nbsp;&nbsp;：'+discountRate+'%</span></div>',
			'   <div><span class="TitleTwo">状&nbsp;&nbsp;&nbsp;&nbsp;态&nbsp;&nbsp;&nbsp;：'+statusResult+'</span></div>',
			'</div>'
		];
	}
	
	var htmls = [
		'<li class="table-view-cell">',
		'		<div>',
		'			<div class="redeem-title"><span class="TitleOne">'+loanTitle+'</span></div>',
		'			<div class="cmw_list_row">',
		'				<div><span class="TitleTwo">剩余本金：￥'+xmoney+'</span></div>',
		'				<div><span class="TitleTwo">剩余期限：</span><span class="TitleTrhee mui-orange">'+leftPeriod+'个月</span></div>',
		'			</div>',
		'			<div class="cmw_list_row">',
		'				<div><span class="TitleTwo">年化收益：</span><span class="TitleTrhee mui-blue">'+rateYear+'%</span></div>',
				subHtmls.join("  "),
		'		</div>',
		'	</li>',
		'   <div style="padding-top: 5px;background: #f3f3f3;"></div>'
	];
	return htmls.join(" ");
}
function initListPicker(feeStart,feeEnd){
	(function($, doc) {
		$.init({selectIndex:1});
		 
		 
		$.ready(function() {
			var dataArr = [];
			var selectIndex = 0;
			for(var i=feeStart; i<=feeEnd; i+=0.5){
				if(i < 0){
					selectIndex++;
				}
				var val = i+"";
				var data = {value:val,text:val};
				dataArr[dataArr.length] = data;
			}
			
			//普通示例
			var userPicker = new $.PopPicker();
			userPicker.selectIndex = selectIndex;
			userPicker.setData(dataArr);
			
			for(var i=0,count=zrlIdArr.length; i<count; i++){
				var _zrlId = zrlIdArr[i];
				var input_zrlId = CmwMcore.$(_zrlId);
				MeventMgr.onTouchstart(input_zrlId,function(event,self){
					userPicker.show(function(items) {
						var data = items[0];
						self.value = data.value;
					});
					return false;
				});
			}
		});
	})(mui, document);	
}
var agree_xy = CmwMcore.$("agree_xy");
MeventMgr.onTouchstart(agree_xy, function(event, self) {
	var loanRecordId = $("#loanRecordIds_val").text();
	var discountRate = $("#discounts_val").text();
	var fromUserId = $("#fromUserId_val").text();
	var cfg = {
		pars: {
			loanRecordId: loanRecordId,
			discountRate: discountRate,
			fromUserId: fromUserId
		}
	};
	MuiEventMgr.open('../protocol/tranProtocol.html', cfg);
	return false;
});
